
#include <cstdio>
#include <BPainter>
#include "WaveViewer.h"

WaveViewer::WaveViewer(BWidget* parent) : BWidget(parent)
{
	this->setBorder(5);
	this->setMargin(10);
}
WaveViewer::~WaveViewer()
{

}

void WaveViewer::setWave(const BAudio* audio)
{
	_audio = (BAudio*)audio;
	_dirty = true;
	this->fresh();
}
const BAudio* WaveViewer::audio() const
{
	return _audio;
}

void WaveViewer::freshEvent(const BEvent& event)
{
	BWidget::freshEvent(event);
	if (_dirty)
	{
		int cx = this->centerRect().x();
		int cy = this->centerRect().y();
		int cw = this->centerRect().width();
		int ch = this->centerRect().height();
		int bottom = this->centerRect().bottom();
		const BByteArray* bytes = _audio->bytes();
		int duration = _audio->duration();
		int size = bytes->size() * 1000 / duration;
		size = bMin(size, bytes->size());
		static BByteArray buffer;
		buffer.reset();
		buffer.append(*bytes, bytes->size() - size, size);
		Format format = _audio->format();
		if (format == Format_UChar)
		{
			const unsigned char* data = buffer.data();
			_points.resize(size);
			for (int i = 0; i < _points.size(); i++)
			{
				int y = (int)(bottom - data[i] / 255.0f * ch);
				int x = (int)(i / (float)_points.size() * cw);
				_points[i].set(x, y);
			}
		}
		if (format == Format_UShort)
		{
			const unsigned short* data = (const unsigned short*)buffer.data();
			_points.resize(size / 2);
			for (int i = 0; i < _points.size(); i++)
			{
				int y = (int)(bottom - data[i] / 65535.0f * ch);
				int x = (int)(i / (float)_points.size() * cw);
				_points[i].set(x, y);
			}
		}
		_dirty = false;
	}
}
void WaveViewer::paintEvent(const BEvent& event)
{
	BWidget::paintEvent(event);
	BPainter painter(this);
	painter.setColor(200, 0, 0);
	painter.drawLineStrip(_points);
}
